home *** CD-ROM | disk | FTP | other *** search
- Path: news.rchland.ibm.com!usenet
- From: Philip Staite <pstaite+@rchland.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Binary Converter
- Date: Mon, 08 Apr 1996 07:23:05 -0500
- Organization: IBM Rochester, MN
- Message-ID: <31690529.41C6@rchland.ibm.com>
- References: <31618729.6BC22935@oberon.hs.gettysburg.edu> <828744431snz@j-bg.demon.co.uk>
- NNTP-Posting-Host: powertool.rchland.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; AIX 1)
-
- John Sargent wrote:
- >
- > In article <31618729.6BC22935@oberon.hs.gettysburg.edu> ** none ** writes:
- >
- > > I am working on a binary converter function, and it isn't working
- > > correctly. I am basically passing a number to be converted to the
- > > function, then using if statements to see which place of the number
- > > would be in, dividing, and then doing the same with the remainder, until
- > > the ones place. Each time the number fits one of the if statements, it
- > > copies a one to a string, and for every if it does not fit, it copies a
- > > zero. Lastly it returns the converted binary number. Does anyone know a
- > > better way of doing this? Or why mine would not be working (I would
- > > include the source here, but I had some trouble, and had to reformat my
- > > drive, so it is gone as of now). If you can help, please email me at
- > > mnicastr@oberon.hs.gettysburg.edu
- > > Thanks
- >
- > void ToBin(unsigned int in, char * out)
- > {
- > unsigned mask = 0x8000;
- > int bit;
- >
- > *out = 0;
- >
- > for ( bit = 0; bit < 16; bit++)
- > {
- > if ( in & mask )
- > strcat(out, "1");
- > else
- > strcat(out, "0");
- >
- > mask = mask >> 1;
- > }
- > }
-
- How about this version, which is independent of the size of ints...
-
-
- void ToBin( unsigned i, char* s ) {
- for( unsigned m = 1 << ( sizeof(unsigned) * 8 - 1 ) ; m ; m >>= 1 )
- *s++ = m & i ? '1' : '0';
- *s = '\0'; }
-
-
-
-
-
- --
-
- Phil Staite, (507) 253-2529, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-